package com.laboratory.manage.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laboratory.manage.controller.FileController;
import com.laboratory.manage.dao.MonographDao;
import com.laboratory.manage.entity.MonographEntity;
import com.laboratory.manage.service.MonographService;
import com.laboratory.manage.utils.FileUtils;
import com.laboratory.manage.utils.PageUtils;
import com.laboratory.manage.utils.Query;
import com.laboratory.manage.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Date;
import java.util.Map;

@Service
public class MonographServiceImpl extends ServiceImpl<MonographDao, MonographEntity> implements MonographService {

    @Autowired
    private MonographDao monographDao;

    @Value("${file.upload-dir}")
    private String uploadPath;

    //上传
    @Override
    public R upLoadMonograph(MonographEntity monograph) {
        try {
            String filePath = FileController.getFilePath();
            monograph.setMonographPath(filePath);
            monographDao.insert(monograph);
            return R.ok();
        } catch (Exception e) {
            return R.error();
        }
    }


    /**
     * 修改
     * @param monograph
     * @return
     */
    @Override
    public R updateMonograph(MonographEntity monograph) {
        try {
            monograph.setUpdateTime(new Date());
            monographDao.updateById(monograph);
            return R.ok();
        } catch (Exception e) {
            return R.error();
        }
    }


    @Override
    public boolean deleteByIds(Long[] ids) {
        //System.out.println(ids);
        for (int i = 0; i < ids.length; i++) {
            MonographEntity monographEntity = monographDao.selectById(ids[i]);
            //获取存储的路径
            String monographPath = monographEntity.getMonographPath();
            //获取作者路径
            String prePath = FileUtils.extractDirectory(monographPath);
            File file1 = new File(prePath);
            //获取以名字结尾的文件夹路径
            File file = new File(monographPath);
            if (file.exists()){
                file.delete();
                monographDao.deleteById(ids[i]);
            }
            //作者目录下没有论文后，删除作者目录
            if (file1 .isDirectory() && file1 .list().length == 0){
                file1.delete();
            }
        }

        return true;
    }



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MonographEntity> page = this.page(new Query<MonographEntity>().getPage(params),
                new QueryWrapper<MonographEntity>()
        );
        return new PageUtils(page);
    }
}
